package com.xiaoyao.market.fragment;

import com.xiaoyao.market.R;
import com.xiaoyao.market.bean.GoodsInfo;
import com.xiaoyao.market.utils.Constants;
import com.example.market.activity.BoxActivity;
import com.example.market.activity.DetailActivity;
import com.example.market.activity.FavorActivity;
import com.example.market.activity.MainActivity;
import com.example.market.activity.OrdersActivity;
import com.example.market.activity.PurseActivity;
import com.example.market.activity.SearchActivity;
import com.example.market.activity.WebActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.nineoldandroids.animation.ObjectAnimator;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 *
 */
public class HomeFragment extends Fragment implements OnClickListener {

	private PullToRefreshScrollView mPtrScrollView;

	private ViewPager mPager;
	private int[] mBanner = new int[] { R.drawable.img_home_banner1,
			R.drawable.img_home_banner2, R.drawable.img_home_banner3,
			R.drawable.img_home_banner4 };
	private GoodsInfo[] mInfos;
	private ImageView mImageView;
	private ImageView mImgCover;
	private int mLastPos;// 记录上一次ViewPager的位置
	private boolean isDragging;// 是否被拖拽
	private boolean isFoucusRight; // ScrollView是否滚动到右侧
	private View layout;
	private int secondCount = 10800; // 倒计时3小时

	private HorizontalScrollView mScrollView;
	private HorizontalScrollView mScrollView2;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		initGoodsInfos();
		if (layout != null) {
			// 防止多次new出片段对象，造成图片错乱问题
			return layout;
		}
		layout = inflater.inflate(R.layout.fragment_home, container, false);
		initView();
		initPager();
		autoScroll();
		initTimer();
		return layout;
	}

	private void initGoodsInfos() {
		mInfos = new GoodsInfo[] {
				new GoodsInfo(
						"100001",
						"Levi's李维斯男士休闲时尚潮流短袖T恤82176-0005 灰/白 L",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods01.jpg",
						"服饰鞋包", 153.00, "好评96%", 1224, 1, 0),
				new GoodsInfo(
						"100002",
						"Levi's李维斯505系列男士舒适直脚牛仔裤00505-1185 牛仔色 36 34",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods02.jpg",
						"服饰鞋包", 479.00, "好评95%", 645, 0, 0),
				new GoodsInfo(
						"100003",
						"GXG男装 京东专供 2015夏装新款 男士时尚白色修身圆领短袖T恤#42244315 白色 M",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods03.jpg",
						"服饰鞋包", 149.00, "暂无评价", 1856, 0, 0),
				new GoodsInfo(
						"100004",
						"Apple iPad mini ME276CH/A 配备 Retina 显示屏 7.9英寸平板电脑 （16G WiFi版）深空灰色",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods04.jpg",
						"电脑数码", 2138.00, "好评97%", 865, 0, 0),
				new GoodsInfo(
						"100005",
						"联想（ThinkPad）轻薄系列E450C(008CD) 14英寸笔记本电脑 （i3-4005U 4GB 500G+8GSSD 1G WIN8.1）",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods05.jpg",
						"电脑数码", 3299.00, "好评95%", 236, 0, 0),
				new GoodsInfo(
						"100006",
						"罗技（Logitech）G502 自适应游戏鼠标",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods06.jpg",
						"服饰鞋包", 499.00, "好评95%", 115, 0, 0),
				new GoodsInfo(
						"100007",
						"瑞士军刀（Swissgear）SA7777WH 12英寸时尚休闲型双肩电脑背包 米白色",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods07.jpg",
						"服饰鞋包", 199.00, "好评95%", 745, 0, 0),
				new GoodsInfo(
						"100008",
						"创见（Transcend） 340系列 256G SATA3 固态硬盘(TS256GSSD340)",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods08.jpg",
						"电脑数码", 569.00, "好评95%", 854, 1, 0),
				new GoodsInfo(
						"100009",
						"佳能（Canon） EOS 700D 单反套机 （EF-S 18-135mm f/3.5-5.6 IS STM镜头）",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods09.jpg",
						"电脑数码", 5099.00, "好评94%", 991, 0, 0),
				new GoodsInfo(
						"100010",
						"飞轮威尔（F-WHEEL) 智能电动独轮车 自平衡独轮车 海豚系列拉杆 支架 音响 蓝牙 白色D1续航20KM无支架",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods10.jpg",
						"运动户外", 2999.00, "好评93%", 1145, 0, 0),
				new GoodsInfo(
						"100011",
						"永久21速26寸铝合金自行车 禧玛诺变速 铝肩可调锁死减震山地车 QJ243 自营",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods11.jpg",
						"运动户外", 1088.00, "好评92%", 909, 0, 0),
				new GoodsInfo(
						"100012",
						"我们都一样年轻又彷徨 自营",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods12.jpg",
						"图书音像", 25.40, "好评95%", 1443, 0, 0),
				new GoodsInfo(
						"100013",
						"近在远方",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods13.jpg",
						"图书音像", 19.70, "好评98%", 3702, 0, 0),
				new GoodsInfo(
						"100014",
						"自在的旅行",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods14.jpg",
						"图书音像", 38.40, "好评97%", 442, 1, 0),
				new GoodsInfo(
						"100015",
						"Photoshop专业抠图技法 赠光盘1张",
						"http://7xi38r.com1.z0.glb.clouddn.com/@/server_anime/goodsicons/goods15.jpg",
						"图书音像", 57.80, "好评93%", 765, 0, 0) };
	}

	private void initView() {
		layout.findViewById(R.id.img_home_category).setOnClickListener(this);
		layout.findViewById(R.id.img_home_search_code).setOnClickListener(this);
		layout.findViewById(R.id.layout_my_focus).setOnClickListener(this);
		layout.findViewById(R.id.layout_logistics).setOnClickListener(this);
		layout.findViewById(R.id.layout_top_up).setOnClickListener(this);
		layout.findViewById(R.id.layout_film).setOnClickListener(this);
		layout.findViewById(R.id.layout_game_top_up).setOnClickListener(this);
		layout.findViewById(R.id.layout_purse).setOnClickListener(this);
		layout.findViewById(R.id.layout_jingdou).setOnClickListener(this);
		layout.findViewById(R.id.layout_more).setOnClickListener(this);
		layout.findViewById(R.id.layout_home_search).setOnClickListener(this);
		layout.findViewById(R.id.layout_discount).setOnClickListener(this);
		layout.findViewById(R.id.layout_discount_phone).setOnClickListener(this);
		layout.findViewById(R.id.img_discount_banner).setOnClickListener(this);
		layout.findViewById(R.id.layout_recom).setOnClickListener(this);
		layout.findViewById(R.id.layout_recom2).setOnClickListener(this);
		layout.findViewById(R.id.layout_recom3).setOnClickListener(this);
		layout.findViewById(R.id.layout_recom4).setOnClickListener(this);
		layout.findViewById(R.id.layout_recom5).setOnClickListener(this);
		layout.findViewById(R.id.img_banner6).setOnClickListener(this);
		layout.findViewById(R.id.img_banner7).setOnClickListener(this);
		layout.findViewById(R.id.layout_special).setOnClickListener(this);
		layout.findViewById(R.id.layout_special2).setOnClickListener(this);
		layout.findViewById(R.id.layout_special3).setOnClickListener(this);
		layout.findViewById(R.id.layout_special4).setOnClickListener(this);
		layout.findViewById(R.id.img_banner8).setOnClickListener(this);
		layout.findViewById(R.id.img_banner9).setOnClickListener(this);
		mPtrScrollView = (PullToRefreshScrollView) layout
				.findViewById(R.id.ptrScrollView_home);
		mPtrScrollView
				.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
					public void onRefresh(
							PullToRefreshBase<ScrollView> refreshView) {
						new GetDataTask().execute();
					}
				});

		mImgCover = (ImageView) layout.findViewById(R.id.img_cover);
		mImageView = (ImageView) layout.findViewById(R.id.img_indicator01);
		mScrollView = (HorizontalScrollView) layout
				.findViewById(R.id.layout_recom_banner);
		mScrollView2 = (HorizontalScrollView) layout
				.findViewById(R.id.layout_special_banner);
	}

	private void activeCategory() {
		MainActivity activity = (MainActivity) getActivity();
		activity.activeCategory();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		// 将layout从父组件中移除
		ViewGroup parent = (ViewGroup) layout.getParent();
		parent.removeView(layout);
	}

	private void initPager() {
		mPager = (ViewPager) layout.findViewById(R.id.pager_banner);
		FragmentManager fm = getChildFragmentManager();
		MyPagerAdapter adapter = new MyPagerAdapter(fm);
		mPager.setAdapter(adapter);
		mPager.setCurrentItem(1000);
		mPager.setOnPageChangeListener(new MyPagerListener());
	}

	/**
	 * 自动滚动
	 */
	private void autoScroll() {
		mPager.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (!isDragging) {
					// 若用户没有拖拽，则自动滚动
					mPager.setCurrentItem(mPager.getCurrentItem() + 1);
				}
				if (isFoucusRight) {
					mScrollView.fullScroll(ScrollView.FOCUS_LEFT);
				} else {
					mScrollView.fullScroll(ScrollView.FOCUS_RIGHT);
				}
				isFoucusRight = !isFoucusRight;
				mPager.postDelayed(this, 3000);
			}
		}, 3000);
		mScrollView2.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (isFoucusRight) {
					mScrollView2.fullScroll(ScrollView.FOCUS_RIGHT);
				} else {
					mScrollView2.fullScroll(ScrollView.FOCUS_LEFT);
				}
				mScrollView2.postDelayed(this, 3000);
			}
		}, 4000);
	}

	/**
	 * 倒计时
	 */
	private void initTimer() {
		final TextView tvHour = (TextView) layout.findViewById(R.id.tv_hour);
		final TextView tvMinute = (TextView) layout
				.findViewById(R.id.tv_minute);
		final TextView tvSecond = (TextView) layout
				.findViewById(R.id.tv_second);
		tvHour.post(new Runnable() {

			@Override
			public void run() {
				if (secondCount > 0) {

					secondCount--;
					int h = secondCount / 3600;
					int m = secondCount / 60 % 60;
					int s = secondCount % 60;
					StringBuffer hour = new StringBuffer();
					StringBuffer minute = new StringBuffer();
					StringBuffer second = new StringBuffer();
					if (h < 10) {
						hour.append(0);
					}
					if (m < 10) {
						minute.append(0);
					}
					if (s < 10) {
						second.append(0);
					}
					hour.append(h);
					minute.append(m);
					second.append(s);
					tvHour.setText(hour);
					tvMinute.setText(minute);
					tvSecond.setText(second);
					tvHour.postDelayed(this, 1000);
				}
			}
		});
	}

	class MyPagerAdapter extends FragmentStatePagerAdapter {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			BannerItemFragment fragment = new BannerItemFragment();
			fragment.setResId(mBanner[position % mBanner.length]);
			fragment.setGoodsInfo(mInfos[position % mBanner.length]);
			return fragment;
		}

		@Override
		public int getCount() {
			return 10000;
		}

	}

	class MyPagerListener implements OnPageChangeListener {

		@Override
		public void onPageScrolled(int position, float positionOffset,
								   int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			int width = mImgCover.getWidth();
			LayoutParams layoutParams = (LayoutParams) mImageView
					.getLayoutParams();
			int rightMargin = layoutParams.rightMargin;
			int endPos = (width + rightMargin) * (position % 4);
			int startPos = 0;
			if (mLastPos < position) {
				// 图片向右移动
				startPos = (width + rightMargin) * (position % 4 - 1);
			} else {
				// 图片向左移动
				startPos = (width + rightMargin) * (position % 4 + 1);
			}
			ObjectAnimator.ofFloat(mImgCover, "translationX", startPos, endPos)
					.setDuration(300).start();
			mLastPos = position;
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
				case ViewPager.SCROLL_STATE_DRAGGING:
					// 用户拖拽
					isDragging = true;
					break;
				case ViewPager.SCROLL_STATE_IDLE:
					// 空闲状态
					isDragging = false;
					break;
				case ViewPager.SCROLL_STATE_SETTLING:
					// 被释放时
					isDragging = false;
					break;

				default:
					break;
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.img_home_category: // 切换到分类
				activeCategory();
				break;

			case R.id.img_home_search_code: // 二维码扫描
				((MainActivity) getActivity()).scanQRCode();
				break;

			case R.id.layout_home_search:
				gotoSearch();
				break;

			case R.id.layout_my_focus: // 我的关注
				startActivity(new Intent(getActivity(), FavorActivity.class));
				break;

			case R.id.layout_logistics: // 物流查询
				startActivity(new Intent(getActivity(), OrdersActivity.class));
				break;

			case R.id.layout_top_up: // 充值
				Intent intent = new Intent(getActivity(), WebActivity.class);
				intent.putExtra("direction", 1);
				startActivity(intent);
				break;

			case R.id.layout_film: // 电影票
				Intent intent2 = new Intent(getActivity(), WebActivity.class);
				intent2.putExtra("direction", 3);
				startActivity(intent2);
				break;

			case R.id.layout_game_top_up: // 游戏充值
				Intent intent3 = new Intent(getActivity(), WebActivity.class);
				intent3.putExtra("direction", 2);
				startActivity(intent3);
				break;

			case R.id.layout_purse: // 小金库
				startActivity(new Intent(getActivity(), PurseActivity.class));
				break;

			case R.id.layout_jingdou: // 领取京豆
				Intent intent4 = new Intent(getActivity(), WebActivity.class);
				intent4.putExtra("direction", 4);
				startActivity(intent4);
				break;

			case R.id.layout_more: // 更多
				startActivity(new Intent(getActivity(), BoxActivity.class));
				break;

			case R.id.layout_discount: // 白菜秒杀
				gotoDetail(4);
				break;

			case R.id.layout_discount_phone: // 手机专享
				gotoDetail(5);
				break;

			case R.id.img_discount_banner: // 奶粉放心购
				gotoDetail(6);
				break;

			case R.id.layout_recom: // 值得买
				gotoDetail(7);
				break;

			case R.id.layout_recom2: // 精选推荐
				gotoDetail(8);
				break;

			case R.id.layout_recom3: // 闪购
				gotoDetail(9);
				break;

			case R.id.layout_recom4: // 团购
				gotoDetail(10);
				break;

			case R.id.layout_recom5: // 京东众筹
				gotoDetail(11);
				break;

			case R.id.img_banner6:
				gotoDetail(12);
				break;

			case R.id.img_banner7:
				gotoDetail(13);
				break;

			case R.id.layout_special:	//小食袋
				gotoDetail(0);
				break;

			case R.id.layout_special2:	//爱生活
				gotoDetail(1);
				break;

			case R.id.layout_special3:	//风尚季
				gotoDetail(2);
				break;
			case R.id.layout_special4:	//血压计
				gotoDetail(3);
				break;

			case R.id.img_banner8:
				gotoDetail(13);
				break;
			case R.id.img_banner9:
				gotoDetail(14);
				break;

			default:
				break;
		}
	}

	/**
	 * 转到商品详情
	 */
	private void gotoDetail(int index) {
		Intent intent = new Intent(getActivity(), DetailActivity.class);
		intent.putExtra(Constants.INTENT_KEY.INFO_TO_DETAIL, mInfos[index]);
		startActivity(intent);
	}

	private void gotoSearch() {
		Intent intent = new Intent(getActivity(), SearchActivity.class);
		startActivity(intent);
		// activity开启无动画
		getActivity().overridePendingTransition(0, 0);
	}

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {
		protected String[] doInBackground(Void... params) {
			// 下拉刷新
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}
			return null;
		}

		protected void onPostExecute(String[] result) {
			mPtrScrollView.onRefreshComplete();// 关闭刷新动画
		}

	}

}
